package com.lianlb.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.impl.Jdk14Logger;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

public class JdkLoggerSetting implements ServletContextListener {


    public JdkLoggerSetting() {
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
//        this.setLevel(Level.FINE);
    }

    private void setLevel(Level level) {

        InputStream ins = JdkLoggerSetting.class.getResourceAsStream("log.properties");
        try {
            LogManager.getLogManager().readConfiguration(ins);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != ins) {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        LogManager logManager = LogManager.getLogManager();
        Enumeration<String> loggerNames = logManager.getLoggerNames();
        while (loggerNames.hasMoreElements()) {
            String name = loggerNames.nextElement();
            Jdk14Logger jdk14Logger = (Jdk14Logger) LogFactory.getLog(name);
            Logger logger = jdk14Logger.getLogger();
            logger.setLevel(Level.FINE);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
